package com.Cychat.doctor.mapper;

import com.Cychat.commons.entity.pojo.Appointment;
import com.Cychat.commons.entity.vo.TreatmentVo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.Cychat.commons.entity.pojo.Drug;
import com.Cychat.commons.entity.pojo.TreatmentRecord;
import com.Cychat.commons.entity.vo.AppointmentDetailVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
@Mapper
public interface TreatmentRecordMapper extends BaseMapper<TreatmentRecord> {

    /**
     * 分页联表查询诊疗记录（关联预约表，用于过滤医生ID）
     */
    @Select("""
        SELECT tr.*, a.doctor_id  -- 关联预约表的医生ID，用于过滤
        FROM treatment_record tr
        LEFT JOIN appointment a ON tr.appointment_id = a.appointment_id
        ${ew.customSqlSegment}
    """)
    IPage<TreatmentRecord> selectTreatmentPage(
            Page<TreatmentRecord> page,
            @Param(Constants.WRAPPER) Wrapper<TreatmentRecord> queryWrapper
    );

    /**
     * 根据诊疗ID查询详情（关联预约表）
     */
    @Select("""
        SELECT tr.*, a.doctor_id, a.pet_id, a.owner_id, a.symptom, a.appointment_date, a.appointment_time
        FROM treatment_record tr
        LEFT JOIN appointment a ON tr.appointment_id = a.appointment_id
        WHERE tr.treatment_id = #{treatmentId}
    """)
    TreatmentRecord selectTreatmentById(@Param("treatmentId") Integer treatmentId);

    /**
     * 关联查询预约详情（含宠物、主人、主人用户信息）
     */
    @Select("""
        SELECT 
            -- 预约表字段
            a.appointment_id, a.symptom, a.appointment_date, a.appointment_time,
            -- 宠物表字段
            p.pet_id, p.name AS pet_name, p.type AS pet_type, p.breed AS pet_breed,
            p.birthday AS pet_birthday, p.notes AS pet_notes, p.weight AS pet_weight,
            -- 主人表字段
            po.owner_id, po.address AS owner_address, po.emergency_contact,
            -- 主人用户表字段
            u.user_id, u.nick_name AS owner_name
        FROM appointment a
        LEFT JOIN pet p ON a.pet_id = p.pet_id
        LEFT JOIN pet_owner po ON a.owner_id = po.owner_id
        LEFT JOIN user u ON po.user_id = u.user_id
        WHERE a.appointment_id = #{appointmentId}
    """)
    AppointmentDetailVo selectAppointmentDetail(@Param("appointmentId") Integer appointmentId);

    /**
     * 根据药品ID列表查询药品信息
     */
    @Select("<script>" +
            "SELECT drug_id, name, specification, usages, contraindication, price " +
            "FROM drug " +
            "WHERE drug_id IN " +
            "<foreach collection='drugIds' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    List<Drug> selectDrugListByIds(@Param("drugIds") List<Integer> drugIds);
        // 新增：分页查询医生的预约记录
        @Select("SELECT * FROM appointment WHERE doctor_id = #{doctorId} ${ew.customSqlSegment}")
        IPage<Appointment> selectPage(Page<Appointment> page,
                                      @Param("doctorId") Integer doctorId,
                                      @Param(Constants.WRAPPER) Wrapper<Appointment> queryWrapper);


    /**
     * 连表查询当前医生的所有诊疗记录（修复别名+移除药品关联）
     */
    @Select("""
        SELECT 
            -- 诊疗表字段
            tr.treatment_id, tr.appointment_id, tr.diagnosis, tr.treatment_plan, 
            tr.cost, tr.create_date, tr.drug_ids, -- 保留 drug_ids（JSON数组）
            -- 预约表字段：别名改为 appointment.xxx（对应 AppointmentVo 字段）
            a.pet_id AS `appointment.petId`, a.owner_id AS `appointment.ownerId`,
            a.symptom AS `appointment.symptom`, a.appointment_date AS `appointment.appointmentDate`,
            a.appointment_time AS `appointment.appointmentTime`, a.status AS `appointment.status`,
            -- 宠物表字段：别名改为 appointment.pet.xxx（嵌套到 appointment 中的 pet 对象）
            p.name AS `appointment.pet.name`, p.type AS `appointment.pet.type`,
            p.breed AS `appointment.pet.breed`, p.birthday AS `appointment.pet.birthday`,
            p.weight AS `appointment.pet.weight`, p.notes AS `appointment.pet.notes`,
            -- 主人表字段：别名改为 appointment.petOwner.xxx
            po.address AS `appointment.petOwner.address`, 
            po.emergency_contact AS `appointment.petOwner.emergencyContact`,
            -- 主人用户表字段：别名改为 appointment.ownerUser.xxx
            u.nick_name AS `appointment.ownerUser.nickName`
        FROM treatment_record tr
        LEFT JOIN appointment a ON tr.appointment_id = a.appointment_id
        LEFT JOIN pet p ON a.pet_id = p.pet_id
        LEFT JOIN pet_owner po ON a.owner_id = po.owner_id
        LEFT JOIN user u ON po.user_id = u.user_id
        WHERE a.doctor_id = #{doctorId} -- 筛选当前医生
        ORDER BY tr.create_date DESC
    """)
    List<TreatmentVo> selectDoctorTreatmentList(@Param("doctorId") Integer doctorId);

    /**
     * 连表查询诊疗详情（修复别名+移除药品关联）
     */
    @Select("""
        SELECT 
            tr.treatment_id, tr.appointment_id, tr.diagnosis, tr.treatment_plan, 
            tr.cost, tr.create_date, tr.drug_ids,
            a.pet_id AS `appointment.petId`, a.owner_id AS `appointment.ownerId`,
            a.symptom AS `appointment.symptom`, a.appointment_date AS `appointment.appointmentDate`,
            a.appointment_time AS `appointment.appointmentTime`, a.status AS `appointment.status`,
            p.name AS `appointment.pet.name`, p.type AS `appointment.pet.type`,
            p.breed AS `appointment.pet.breed`, p.birthday AS `appointment.pet.birthday`,
            p.weight AS `appointment.pet.weight`, p.notes AS `appointment.pet.notes`,
            po.address AS `appointment.petOwner.address`, 
            po.emergency_contact AS `appointment.petOwner.emergencyContact`,
            u.nick_name AS `appointment.ownerUser.nickName`
        FROM treatment_record tr
        LEFT JOIN appointment a ON tr.appointment_id = a.appointment_id
        LEFT JOIN pet p ON a.pet_id = p.pet_id
        LEFT JOIN pet_owner po ON a.owner_id = po.owner_id
        LEFT JOIN user u ON po.user_id = u.user_id
        WHERE tr.treatment_id = #{treatmentId} AND a.doctor_id = #{doctorId}
    """)
    TreatmentVo selectDoctorTreatmentDetail(
            @Param("treatmentId") Integer treatmentId,
            @Param("doctorId") Integer doctorId
    );
}